package com.aspirecn.auth.config.security;

import java.io.IOException;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter;

import com.aspirecn.auth.infrastructure.OAuth2Constants;


public class CustomClientCredentialsTokenEndpointFilter extends ClientCredentialsTokenEndpointFilter {
	
	private static final Logger LOG = LoggerFactory.getLogger(CustomClientCredentialsTokenEndpointFilter.class);

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException, IOException, ServletException {
		LOG.info("test222222222222222222222222222");
		Cookie cookieRequest = null;
		String key = null;
		
		try {
			final Authentication authentication = super.attemptAuthentication(request, response);
			final String captcha = request.getParameter(OAuth2Constants.CAPTCHA_URI_PARAMETER);

			final Cookie[] cookies = request.getCookies();
			if (cookies == null || cookies.length <= 0) {
				LOG.error("captcha cookies error:{}", Arrays.toString(cookies));
				throw new CaptchaException("验证码错误");
			}
			
			for (final Cookie cookie : cookies) {
				if (OAuth2Constants.CAPTCHA_COOKIE_KEY.equals(cookie.getName())) {
					key = cookie.getValue();
					cookieRequest = cookie;
					break;
				}
			}
			
			if (key == null || key == "") {
				LOG.error("captcha key error:{}", key);
				throw new CaptchaException("验证码错误");
			}

			String captchaValue =  redisTemplate.opsForValue().get(OAuth2Constants.CAPTCHA_REDIS_PATH + key);
			
			if (captcha == null || !captcha.equalsIgnoreCase(captchaValue)) {
				LOG.error("captcha error  captcha:{}  captcha cache:{}", captcha, captchaValue);
				throw new CaptchaException("验证码错误");
			}	
			//TODO 验证帐号密码
			return authentication;
			
		} finally {
		    if (cookieRequest != null) {
		    	cookieRequest.setValue(null);
		    	cookieRequest.setMaxAge(0);
		    	cookieRequest.setPath("/");
		    	cookieRequest.setDomain("");
		    	response.addCookie(cookieRequest);
			    if (redisTemplate != null && key != null) {
				      redisTemplate.delete(OAuth2Constants.CAPTCHA_REDIS_PATH + key);
				}
		    }
		}
	}
}